package com.rjkj.medicalwaste.ui.outbound

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.fragment.app.activityViewModels
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.findNavController
import com.rjkj.medicalwaste.MainActivity
import com.rjkj.medicalwaste.R
import com.rjkj.medicalwaste.base.BaseFragment
import com.rjkj.medicalwaste.bean.CodeType
import com.rjkj.medicalwaste.databinding.FragmentOutboundScanBinding
import com.rjkj.medicalwaste.livedatabus.LiveDataBus
import com.rjkj.medicalwaste.utils.TimeUtils
import com.rjkj.medicalwaste.viewmodels.OutboundScanViewModel
import com.rjkj.medicalwaste.viewmodels.OutboundViewModel
import com.rjkj.medicalwaste.viewmodels.UserViewModel
import com.rjkj.medicalwaste.viewmodels.provider.MainViewModelProvider
import com.rjkj.zxinglibrary.zxing.android.CaptureActivity
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch


class OutboundScanFragment : BaseFragment<FragmentOutboundScanBinding>() {
    private val viewModel: OutboundScanViewModel by viewModels()
    private val userViewModel: UserViewModel by activityViewModels {
        MainViewModelProvider.provideUserModel(requireContext())
    }
    private val outboundViewModel: OutboundViewModel by viewModels {
        MainViewModelProvider.provideOutboundViewModel(requireContext())
    }
    private lateinit var startActivity: ActivityResultLauncher<Intent>
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        startActivity =
            registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
                val resultCode = it.resultCode
                if (resultCode == Activity.RESULT_OK) {
                    val data = it.data?.extras?.getString("codedContent") ?: ""
                    Log.e(TAG, "onCreate: ${resultCode}+${data}")
                    doScanCode(data)
                } else {
                    showTip("扫码失败")
                }

            }
    }

    override fun dealCustomScanData(data: String) {
        super.dealCustomScanData(data)
        doScanCode(data)
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        // Inflate the layout for this fragment
        val binding = FragmentOutboundScanBinding.inflate(inflater, container, false)
        binding.scanData = viewModel
        binding.lifecycleOwner = viewLifecycleOwner
        onSubscribeUi(binding)
        initKeyEvent()
        return binding.root
    }

    override fun onSubscribeUi(binding: FragmentOutboundScanBinding) {
        initTip(viewModel)
        initDialog(userViewModel)
        binding.pic.setOnClickListener {
            scanWithCustomUI()
        }
        binding.tvDisposal.setOnClickListener {
            scanWithCustomUI()
        }
        LiveDataBus.get().with(MainActivity.SCAN_DATA, String::class.java).observe(
            viewLifecycleOwner, {
                doScanCode(it)
            })
    }

    private fun doScanCode(s: String) {
        checkCode(s).let { type ->
            when (type) {
                CodeType.Recycle -> {
                    userViewModel.checkLogin(s).observe(viewLifecycleOwner, { user ->
                        if (user != null) {
                            viewModel.disposal.value = user.name
                            userViewModel.disposalUser.value = user
                            if (!TextUtils.isEmpty(viewModel.disposal.value)) {
                                lifecycleScope.launch {

                                    if (userViewModel.setting.value?.infoMode == 1||userViewModel.setting.value?.infoMode == 2) {
                                        userViewModel.uploadEvent.value = true
                                        delay(500)
                                        val historyInfo2 =
                                            outboundViewModel.getWaitHandoverGarbageList2(
                                                url = userViewModel.getUrl(),
                                                user.qrcode,
                                                serialNum = userViewModel.getSerial(),
                                            )
                                        if (!historyInfo2.isNullOrEmpty()) {
                                            outboundViewModel.handover(
                                                codes = historyInfo2.map {
                                                    it.garbageBoxQRCode
                                                },
                                                handoverDeviceSN = userViewModel.getSerial(),
                                                handoverCleanerQRCode = userViewModel.cleanerUser.qrcode,
                                                handoverQRCode = user.qrcode,
                                                handoverTime = TimeUtils.getYMDHMSTime(),
                                                url = userViewModel.getUrl()
                                            )
                                            showTip("出库成功")
                                        } else {
                                            showTip("无可出库数据")
                                        }
                                        userViewModel.uploadEvent.value = false
                                        delay(500)
                                        requireActivity().onBackPressed()
                                    } else {
                                        viewModel.tips.value = "登录成功！"
                                        delay(250L)
                                        findNavController().navigate(R.id.action_outboundScanFragment_to_outboundMainFragment)
                                    }

                                }
                            }
                        } else {
                            viewModel.disposal.value = ""
                            viewModel.tips.value = "未查询到该用户！"
                        }
                    })
                }
//                CodeType.StagingRoom -> {
//                    userViewModel.checkLogin(s).observe(viewLifecycleOwner, { user ->
//                        if (user != null) {
//                            viewModel.stagingRoom.value = user.name
//                            viewModel.tips.value = "登录成功！"
//                            userViewModel.stagingRoomUser.value = user
//                            if (!TextUtils.isEmpty(viewModel.disposal.value) && !TextUtils.isEmpty(viewModel.stagingRoom.value)) {
//                                lifecycleScope.launch {
//                                    delay(250L)
//                                    findNavController().navigate(R.id.action_outboundScanFragment_to_outboundMainFragment)
//                                }
//                            }
//
//                        } else {
//                            viewModel.disposal.value = ""
//                            viewModel.tips.value = "未查询到该用户！"
//                        }
//                    })
//                }
                else -> {
                    showTip("请勿扫描${type.alias}")
                }
            }

        }
    }


}